package br.com.vfsb.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;





import br.com.vfsb.entity.CompraLocal;
import br.com.vfsb.util.HibernateUtil;

public class CompraLocalDAO {

	public void salvar(CompraLocal c){

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		try {

			tx = session.beginTransaction();
			session.save(c);
			tx.commit();
			//session.close();
			System.out.println("Salvo com sucesso.......");

		} catch (RuntimeException e) {
			if(tx != null){
			tx.rollback();
			session.close();
			System.out.println("Erroo ao salvar......."+e);
			}
			
		}finally{
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<CompraLocal> listar(){
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<CompraLocal> cl = null;
				
		try{
		
			Query consulta = session.getNamedQuery("CompraLocal.listar");
			cl = consulta.list();
			
		}catch(RuntimeException e){
			throw e;
		}finally{
			session.close();
		}
		return cl;
	}
	//lazy load
	@SuppressWarnings("unchecked")
	public List<CompraLocal> findPlayers(int start, int max){
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<CompraLocal> cl = null;
	   
	    
		try{
			//listagem por demanda
			Query consulta = session.getNamedQuery("CompraLocal.listar");
			consulta.setFirstResult(start);
			consulta.setMaxResults(max);
			cl = consulta.list();
			
		}catch(RuntimeException e){
			throw e;
		}finally{
			session.close();
		}
		return cl;
	}
	/*
	public int countPlayersTotal(){
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		
		Query consulta = session.createQuery("SELECT COUNT(*) FROM CompraLocal compralocal");	

		return cl;
	}

	*/
}
